(function(){
    function Game(){
        this.food = new Food();
        this.snake = new Snake();
        window.Snake = null;
        window.Food = null;
    }
    //操纵键盘事件
    function OnKeyboard(snake){
        document.onkeydown = function(e){
            var key = e.keyCode;//37 ~ 40
            switch (key){
                case 37://左
                if(snake.direction !== 'right'){
                    snake.direction = 'left';
                }
                    break;
                case 38://上
                if(snake.direction !== 'down'){
                    snake.direction = 'up';
                }
                    break;
                case 39://右
                if(snake.direction !== 'left'){
                    snake.direction = 'right';
                }
                    break;
                case 40://下
                if(snake.direction !== 'up'){
                    snake.direction = 'down';
                }
                    break;
            }
        }
    }
    //游戏结束
    function gameEnd(timer){
        clearInterval(timer);
        alert('游戏结束')
        window.location.reload();
    }
    Game.prototype.start = function(){
        this.food.render();
        this.snake.render();
        OnKeyboard(this.snake);
        var that =this;
        var timer = setInterval(function(){
            var head = that.snake.bodys[0];
            if(head.x < 0 || head.x > window.mapSize){
                gameEnd(timer)
            }
            if(head.y < 0 || head.y > window.mapSize){
                gameEnd(timer)
            }
            for(var i = 1; i < that.snake.bodys.length; i++){
                var bodyItem = that.snake.bodys[i];
                if(head.x === bodyItem.x && head.y === bodyItem.y){
                    gameEnd(timer);
                }
            }
            that.snake.move(that.food);
            that.snake.render();
        },150)
    }
    window.game = new Game();
    game.start();
}())
